import store from '../store'
let t = null;
const lian = 42161;
let lianOne = [{
	chainId:'',
	chainName:'Arbitrum One',
	nativeCurrency:{
		name:'ETH',
		symbol:'ETH',
		decimals:18
	},
	rpcUrls:['https://arbitrum-mainnet.infura.io'],
	blockExplorerUrls:['https://explorer.arbitrum.io']
}];
let lianTwo = [{
	chainId: '',
	chainName: 'Sepolia测试网络',
	nativeCurrency: {
		name: 'SepoliaETH',
		symbol: 'SepoliaETH',
		decimals: 18
	},
	rpcUrls: ['https://sepolia.infura.io/v3/'],
	blockExplorerUrls: ['https://sepolia.etherscan.io']
}];
let heAddress = store.state.user.heAddress;
let usdtAddress = store.state.user.usdtAddress;
let bdoAddress = store.state.user.bdoAddress;
let heTwoAddress = store.state.user.heTwoAddress;
//合约方法
export default {
	setT(_this) {
		t = _this;
		heAddress = store.state.user.heAddress;
		usdtAddress = store.state.user.usdtAddress;
		bdoAddress = store.state.user.bdoAddress;
		heTwoAddress = store.state.user.heTwoAddress;
	},
	//two最小值
	async kusdLiquidityMinimal(address){
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'kusdLiquidityMinimal',
			type: 'function',
			inputs: [ ]
		}, []);
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			return balance;
		}
		t.$func.myToast(err);
		return 0;
	},
	//one最小值
	async mappingLiquidityMinimal(address){
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'mappingLiquidityMinimal',
			type: 'function',
			inputs: [ ]
		}, []);
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			return balance;
		}
		t.$func.myToast(err);
		return 0;
	},
	async quoteByKusd(address,value){
		// let bu = Number(value) * 10 ** 18;
		// let val = bu.toLocaleString();
		// val = val.replace(/,/g, '');
		
		let val = t.$func.addXiaoTwo(value);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'quoteByKusd',
			type: 'function',
			inputs: [{
				type: 'uint256',
				name: '_count'
			}, ]
		}, [num]);
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = await t.$web3.eth.abi.decodeParameter('uint256', res);
			let value = t.$func.addXiao(balance);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	async quoteByKing(address,value){
		// let bu = Number(value) * 10 ** 18;
		let val = t.$func.addXiaoTwo(value);
		// let val = bu.toLocaleString();
		// val = val.replace(/,/g, '');
		let num = await t.$web3.eth.abi.encodeParameter('uint256',val);
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'quoteByKing',
			type: 'function',
			inputs: [{
				type: 'uint256',
				name: '_count'
			}, ]
		}, [num]);
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = await t.$web3.eth.abi.decodeParameter('uint256', res);
			let value = t.$func.addXiao(balance);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	//查询BNB
	async checkBnb(address) {
		let ret = await t.$web3.eth.getBalance(address);
		let balance = t.$web3.utils.fromWei(ret, 'ether');
		return balance;
	},
	//检查是否有效地址
	checkIsAddress(address,tt) {
		return tt.$web3.utils.isAddress(address)
	},
	//检查链
	async checkLian() {
		let res = '';
		let lianId = lian == 11155111 ? t.$web3.utils.numberToHex(11155111) : t.$web3.utils.numberToHex(42161);
		let lianArr = [];
		if(lian == 11155111){
			lianArr.push(lianTwo[0]);
		}else{
			lianArr.push(lianOne[0]);
		}
		lianArr[0].chainId = lianId;
		try {
			res = await ethereum.request({
				method: 'wallet_switchEthereumChain',
				params: [{
					chainId: lianId
				}]
			})
			return true;
		} catch (e) {
			if (e.code === 4902) {
				try {
					res = await ethereum.request({
						method: 'wallet_addEthereumChain',
						params: lian == 11155111 ? lianTwo : lianOne
					})
					return true;
				} catch (ee) {
					res = ''
					return false;
				}
			} else if (e.code === 4001) {
				return false;
			}
		}
	},
	//send BDO
	async sendBdo(amount,address,func) {
		let val = t.$func.addXiaoTwo(amount,6);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'purchase',
			type: 'function',
			inputs: [
				{
					type: 'uint256',
					name: 'value'
				},
			]
		}, [
			num
		]);
		// const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			// gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		// let gas = await t.$web3.eth.estimateGas(param);
		// param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	//send BDO
	async sendBdoTwo(amount,address,func,ethValue) {
	//purchase
		
		let val = t.$func.addXiaoTwo(amount,18);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'sendToContract',
			type: 'function',
			inputs: [
				{
					type: 'uint256',
					name: 'value'
				},
			]
		}, [
			num
		]);
		// const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heTwoAddress, // Required except during contract publications.
			// gasPrice: gasPrice,
			value:ethValue,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		// let gas = await t.$web3.eth.estimateGas(param);
		// param['gas'] = gas * 2;
	
		
		await t.$web3.eth.sendTransaction(param, func);
	},
	//检查USDT余额
	async checkUsdt(address) {
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'balanceOf',
			type: 'function',
			inputs: [{
				type: 'address',
				name: 'account'
			}, ]
		}, [address]);

		const param = {
			from: address, // must match user's active address.
			to: usdtAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			// let value = balance / 1000000000000000000;
			let value = t.$func.addXiao(balance,6);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	//检查USDT余额
	async checkBdo(address) {
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'balanceOf',
			type: 'function',
			inputs: [{
				type: 'address',
				name: 'account'
			}, ]
		}, [address]);
	
		const param = {
			from: address, // must match user's active address.
			to: bdoAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			// let value = balance / 1000000000000000000;
			let value = t.$func.addXiao(balance,18);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	//授权
	async approve(amount,  address, func) {
		
		let val = t.$func.addXiaoTwo(amount,6);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'approve',
			type: 'function',
			inputs: [{
					type: 'address',
					name: 'spender'
				},
				{
					type: 'uint256',
					name: 'value'
				},
			]
		}, [
			heAddress,
			num
		]);
		// const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: usdtAddress, // Required except during contract publications.
			// gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		// let gas = await t.$web3.eth.estimateGas(param);
		// param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	//bdo授权
	async approveBdo(amount,  address, func) {
		
		let val = t.$func.addXiaoTwo(amount,18);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'approve',
			type: 'function',
			inputs: [{
					type: 'address',
					name: 'spender'
				},
				{
					type: 'uint256',
					name: 'value'
				},
			]
		}, [
			heAddress,
			num
		]);
		// console.log('gasPrice',data)
		// const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: bdoAddress, // Required except during contract publications.
			// gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		// let gas = await t.$web3.eth.estimateGas(param);
		// param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	//授权查询Bdo
	async approveBdoCheck(error, hash, address, func) {
		let res = await t.$web3.eth.getTransactionReceipt(hash);
	
		if (res && res.status) {
			let data = t.$web3.eth.abi.encodeFunctionCall({
				name: 'allowance',
				type: 'function',
				inputs: [{
						type: 'address',
						name: '_owner'
					},
					{
						type: 'address',
						name: 'spender'
					},
				]
			}, [
				address, heAddress
			]);
			const param = {
				from: address, // must match user's active address.
				to: bdoAddress, // Required except during contract publications.
				data: data, // Optional, but used for defining smart contract creation and interaction.
			};
			let error, resn = await t.$web3.eth.call(param);
			let balance = 0;
			if (resn) {
				balance = t.$web3.eth.abi.decodeParameter('uint256', resn);
				balance = t.$func.addXiao(balance,18);
				// balance = balance / (10 ** 18);
			}
			return balance
		} else {
			setTimeout(async () => {
				await func(error, hash)
			}, 2000)
		}
	},
	//授权查询
	async approveCheck(error, hash, address, func) {
		let res = await t.$web3.eth.getTransactionReceipt(hash);

		if (res && res.status) {
			let data = t.$web3.eth.abi.encodeFunctionCall({
				name: 'allowance',
				type: 'function',
				inputs: [{
						type: 'address',
						name: '_owner'
					},
					{
						type: 'address',
						name: 'spender'
					},
				]
			}, [
				address, heAddress
			]);
			const param = {
				from: address, // must match user's active address.
				to: usdtAddress, // Required except during contract publications.
				data: data, // Optional, but used for defining smart contract creation and interaction.
			};
			let error, resn = await t.$web3.eth.call(param);
			let balance = 0;
			if (resn) {
				balance = t.$web3.eth.abi.decodeParameter('uint256', resn);
				balance = t.$func.addXiao(balance,6);
				// balance = balance / (10 ** 18);
			}
			return balance
		} else {
			setTimeout(async () => {
				await func(error, hash)
			}, 2000)
		}
	},

	//激活
	async activate(upAddress, address, func) {
		let up = upAddress;
		if (!upAddress) {
			up = '0x0000000000000000000000000000000000000000'
			// up = '0x9a8e6dFf8a5C0F5A87113ff40B9301424Da499B1'
		}
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'activate',
			type: 'function',
			inputs: [{
				type: 'address',
				name: '_upAddr'
			}, ]
		}, [
			up
		]);

		const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let gas = await t.$web3.eth.estimateGas(param);
		param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},

	//查询结果
	async checkReceipt(error, hash, func) {
		let res = await t.$web3.eth.getTransactionReceipt(hash);
		if (res && res.status) {
			// t.$func.myToast(text);
			return true;
		} else {
			setTimeout(async () => {
				await func(error, hash)
				return false;
			}, 2000)
		}
	},

	//签名
	async sign(data, address) {
		let res = await t.$web3.eth.personal.sign(data, address);
		if (res) {
			return res;
		} else {
			return false;
		}
	},

	//购买USDT到中心化
	async approveKusd(val, address, func) {
		let num = t.$web3.eth.abi.encodeParameter('uint256', val.toString());
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'approveKusd',
			type: 'function',
			inputs: [{
				type: 'uint256',
				name: '_count'
			}, ]
		}, [num]);
		const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let gas = await t.$web3.eth.estimateGas(param);
		param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	//查比例
	async getReserves(myAddress) {
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: "getReserves",
			type: "function",
			inputs: []
		}, []);

		const param = {
			from: myAddress, // must match user's active address.
			to: diAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let error, res = await t.$web3.eth.call(param);
		if(res){
			let value = t.$web3.eth.abi.decodeParameters(['uint256','uint256'], res);
			value[0] = t.$func.addXiao(value[0]);
			value[1] = t.$func.addXiao(value[1]);
			// value[0] = value[0] / 1000000000000000000;
			// value[1] = value[1] / 1000000000000000000;
			return value;
		}

	},
	async tokenOne(myAddress){
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: "token0",
			type: "function",
			inputs: []
		}, []);
		const param = {
			from: myAddress, // must match user's active address.
			to: diAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let error, res = await t.$web3.eth.call(param);
		if(res){
			let value = t.$web3.eth.abi.decodeParameter('address', res);
			
			return value;
		}
	},
	//two添加
	async kusdLiquidity(address,value,func){
		// let bu = Number(value) * 10 ** 18;
		// let val = bu.toLocaleString();
		// val = val.replace(/,/g, '');
		let val = t.$func.addXiaoTwo(value);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'kusdLiquidity',
			type: 'function',
			inputs: [{
				type: 'uint256',
				name: 'kusd'
			}, ]
		}, [num]);
		const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let gas = await t.$web3.eth.estimateGas(param);
		param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	//one添加
	async mappingLiquidity(address,value,valueOne,func){
		// let bu = value * 10 ** 18;
		// let val = bu.toLocaleString();
		// val = val.replace(/,/g, '');
		let val = t.$func.addXiaoTwo(value);
		// let buOne = valueOne * 10 ** 18;
		// let valOne = buOne.toLocaleString();
		// valOne = valOne.replace(/,/g, '');
		let valOne = t.$func.addXiaoTwo(valueOne);
		let num = t.$web3.eth.abi.encodeParameter('uint256',val);
		let numOne = t.$web3.eth.abi.encodeParameter('uint256',valOne);
		let data = await t.$web3.eth.abi.encodeFunctionCall({
			name: 'mappingLiquidity',
			type: 'function',
			inputs: [{
				type: 'uint256',
				name: 'kusd'
			}, {
				type: 'uint256',
				name: 'king'
			},]
		}, [num,numOne]);
		const gasPrice = await t.$web3.eth.getGasPrice();
		let param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			gasPrice: gasPrice,
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let gas = await t.$web3.eth.estimateGas(param);
		param['gas'] = gas * 2;
		await t.$web3.eth.sendTransaction(param, func);
	},
	async mappingLiquidity1(address,value,valueOne){
	
	},
	//我入池King
	async liquidityKingAmount(address){
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'liquidityKingAmount',
			type: 'function',
			inputs: [{
				type: 'address',
				name: 'account'
			}, ]
		}, [address]);
		
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			// let value = balance / 1000000000000000000;
			let value = t.$func.addXiao(balance);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	
	//我入池usdt
	async liquidityKusdAmount(address){
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'liquidityKusdAmount',
			type: 'function',
			inputs: [{
				type: 'address',
				name: 'account'
			}, ]
		}, [address]);
		
		const param = {
			from: address, // must match user's active address.
			to: heAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			// let value = balance / 1000000000000000000;
			let value = t.$func.addXiao(balance);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	},
	//取总量
	async totalSupply(address,toAddress){
		let data = t.$web3.eth.abi.encodeFunctionCall({
			name: 'totalSupply',
			type: 'function',
			inputs: []
		}, []);
		const param = {
			from: address, // must match user's active address.
			to: toAddress, // Required except during contract publications.
			data: data, // Optional, but used for defining smart contract creation and interaction.
		};
		let err, res = await t.$web3.eth.call(param);
		if (!err) {
			let balance = t.$web3.eth.abi.decodeParameter('uint256', res);
			// let value = balance / 1000000000000000000;
			let value = t.$func.addXiao(balance);
			return value;
		}
		t.$func.myToast(err);
		return 0;
	}
}